package com.xpalive.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xpalive.commons.ConstPool;
import com.xpalive.commons.StringPool;
import java.time.LocalDateTime;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class GalaxyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        setCreate(metaObject);
        setModify(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setModify(metaObject);
    }

    private void setCreate(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "creator", () -> ConstPool.UN_KNOW, Long.class);
        this.strictInsertFill(metaObject, "createDatetime", LocalDateTime::now,
            LocalDateTime.class);
        this.strictInsertFill(metaObject, "version", () -> Integer.valueOf(0), Integer.class);
    }

    private void setModify(MetaObject metaObject) {
        this.setFieldValByName("editDatetime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("editor", ConstPool.UN_KNOW, metaObject);
        this.strictInsertFill(metaObject, "deleted", () -> StringPool.NO, String.class);
    }

}
